﻿using System;
using System.Linq;
using Relocation.Data;

namespace Relocation.Service
{
	 public class UserService
	{
		private Relocation.Service.DataModel DataModel;

		public UserService(DataModel dataModel)
		{
			this.DataModel = dataModel;
		}

		/// <summary>
		/// 返回可用的用户名列表
		/// </summary>
		/// <returns></returns>
		public string[] GetUserNameArray()
		{
			//return this.DataModel.Placements.Select(t => t.name).ToArray();
			return this.DataModel.Users.Where(t => t.enable == 1).OrderByDescending(t => t.updated).Select(t => t.name).ToArray();			
		}

		public User Login(string userName, string passWord, out string errorText)
		{
			if (String.IsNullOrEmpty(userName) || string.IsNullOrEmpty(passWord))
			{
				errorText = "用户名或密码不能为空";
				return null;
			}

			User user = this.DataModel.Users.Where(t => userName.Equals(t.name) && passWord.Equals(t.password)).FirstOrDefault();
			if (user == null)
			{
				errorText = "用户名或密码不正确";
				return null;
			}
			if (user.enable != 1)
			{
				errorText = "该用户已经禁用";
				return null;
			}
			user.updated = System.DateTime.Now;
			this.DataModel.Save(user);
			errorText = "";
			return user;
		}
	}
}
